package com.john.booter.module.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.john.booter.annotation.Module;
import com.john.booter.annotation.OptionName;
import com.john.booter.annotation.SubModuleName;
import com.john.booter.domain.entity.User;
import com.john.booter.domain.vo.UserVo;
import com.john.booter.exception.RestSuccess;
import com.john.booter.exception.RestSuccess.Msg;
import com.john.booter.module.user.service.UserService;
import com.john.booter.pagination.DataTable;
import com.john.booter.pagination.Pager;

@SubModuleName(value = "用户管理", root = Module.user, sort=2)
@RestController
@RequestMapping("/user")
public class UserCtrl {
	
	@Autowired
	private UserService service;
	
	@OptionName("列表-WEB")
	@RequestMapping("/datatable")
	public DataTable<User> list(
			@RequestParam(value = "start") Integer start,
			@RequestParam(value = "length") Integer pageSize,
			@RequestParam(value = "search[value]") String searchValue,
			@RequestParam(value = "order[0][column]") Integer orderColumn,
			@RequestParam(value = "order[0][dir]") String orderDir,
			@RequestParam(value = "draw") Integer draw,
			@RequestParam(value = "username", required = false) String username) {
		start = ((start == null || start <= 0) ? 0 : start);
		pageSize = (pageSize == null ? Pager.DEFAULT_PAGE_SIZE : pageSize);
		draw = ((draw == null || draw == 0) ? 1 : draw);
		Pager pg = new Pager();
		pg.setStart(start);
		pg.setPageSize(pageSize);
		pg.setSearchValue(searchValue);
		pg.setOrderColumn(orderColumn);
		pg.setOrderDir(orderDir);
		pg.setDraw(draw);
		DataTable<User> data = service.findDataTable(pg, username);
		return data;
	}
	
	@OptionName("新增")
	@RequestMapping("/add")
	public RestSuccess add(@RequestBody UserVo u) {
		service.add(u);
		return new RestSuccess(Msg.add);
	}
	
	@OptionName("删除")
	@RequestMapping("/delete/{id}")
	public RestSuccess delete(@PathVariable("id") String id) {
		service.delete(id);
		return new RestSuccess(Msg.delete);
	}
	
	@OptionName("更新")
	@RequestMapping("/update")
	public RestSuccess update(@RequestBody UserVo u) {
		service.update(u);
		return new RestSuccess(Msg.update);
	}
	
	@OptionName("列表-APP")
	@RequestMapping("/list")
    public List<User> list() {
		return service.findAll();
    }
	
	@OptionName("详情")
	@RequestMapping("/get/{id}")
	public UserVo get(@PathVariable("id") String id) {
		return service.findById(id);
	}
	
	@OptionName("检验是否存在")
	@RequestMapping("/valid")
	public String valid(@RequestParam("user[username]") String username) {
		if(service.findByUsername(username) == null){
			return "{\"valid\":true}";
		}
		return "{\"valid\":false}";
	}
}
